﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace PingYou.Console
{
    class UrlTrans
    {
        #region 将长链接转换为短链接
        /// <summary>
        /// 将长链接转换为短链接
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string ShortUrl(string url)
        {
            string shortUrl = string.Empty;
            try
            {
                Dictionary<String, String> dicList = new Dictionary<String, String>();
                dicList.Add("source", "3271760578");
                dicList.Add("url_long", url);
                string param = buildQueryStr(dicList);
                var response = DoGet("http://api.t.sina.com.cn/short_url/shorten.json", param);
                response.Wait();
                StreamReader sr = new StreamReader(response.Result.GetResponseStream(), Encoding.UTF8);
                string jsonText = sr.ReadToEnd();
                JArray result = JsonConvert.DeserializeObject(jsonText) as JArray;
                if (result.Count > 0)
                {
                    JToken token = result[0];
                    var data = token.Value<string>("url_short");
                    if (data != null)
                    {
                        shortUrl = data;
                    }
                    else
                    {
                        shortUrl = url;
                    }
                }
            }
            catch (Exception)
            {
                shortUrl = url;
            }
            return shortUrl;
        }

        private static String buildQueryStr(Dictionary<String, String> dicList)
        {
            String postStr = "";

            foreach (var item in dicList)
            {
                postStr += item.Key + "=" + HttpUtility.UrlEncode(item.Value, Encoding.UTF8) + "&";
            }
            postStr = postStr.Substring(0, postStr.LastIndexOf('&'));
            return postStr;
        }

        /// <summary>
        /// 做get请求
        /// </summary>
        private static Task<WebResponse> DoGet(string apiUrl, string paramStr)
        {

            HttpWebRequest req = HttpWebRequest.CreateHttp(apiUrl + "?" + paramStr);
            req.Method = "GET";
            return req.GetResponseAsync();
        }
        #endregion

        #region 将短链接换为长链接
        /// <summary>
        /// 将短链接换为长链接
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string LongUrl(string url)
        {
            string longUrl = string.Empty;
            try
            {
                Dictionary<String, String> dicList = new Dictionary<String, String>();
                dicList.Add("source", "3271760578");
                dicList.Add("url_short", url);


                string param = buildQueryStr(dicList);
                var response = DoGet("http://api.t.sina.com.cn/short_url/expand.json", param);
            
                response.Wait();
                StreamReader sr = new StreamReader(response.Result.GetResponseStream(), Encoding.UTF8);
                string jsonText = sr.ReadToEnd();
                JArray result = JsonConvert.DeserializeObject(jsonText) as JArray;
                if (result.Count > 0)
                {
                    JToken token = result[0];
                    var data = token.Value<string>("url_long");
                    if (data != null)
                    {
                        longUrl = data;
                    }
                    else
                    {
                        longUrl = url;
                    }
                }
            }
            catch (Exception)
            {
                longUrl = url;
            }
            return longUrl;
        }
        #endregion
    }
}
